package com.doctor.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Environment;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.ScrollView;
import com.doctor.ui.R;
import com.doctor.utils.logutils.LogUtils;
import com.doctor.utils.sys.DensityUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 截屏工具(不包括surfaceview的截屏)
 * Created by qy on 2016/12/24.
 */

public class ScreenShot {
    // 获取指定Activity的截屏，保存到png文件
    public static Bitmap takeScreenShot(Activity activity) {
        // View是你需要截图的View
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap b1 = view.getDrawingCache();
        // 获取状态栏高度
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;
        System.out.println(statusBarHeight);
        // 获取屏幕长和高
        int width = activity.getWindowManager().getDefaultDisplay().getWidth();
        int height = activity.getWindowManager().getDefaultDisplay()
                .getHeight();
        // 去掉标题栏
        // Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);
        Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height
                - statusBarHeight);
        view.destroyDrawingCache();
        savePic(b, "/sdcard/screen_test.png");
        return b;
    }

    // 保存到sdcard
    public static void savePic(Bitmap b, String strFileName) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(strFileName);
            if (null != fos) {
                b.compress(Bitmap.CompressFormat.PNG, 90, fos);
                fos.flush();
                fos.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 把View对象转换成bitmap
     */
    public static Bitmap convertViewToBitmap(View view) {
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
        if (bitmap != null) {
            System.out.println("这不是nullde1");
            Log.d("nullde1", "nullde1");
        } else {
            System.out.println("这nullnulllnulnlul");
        }
        return bitmap;
    }

    // 程序入口1
    public static void shoot(Activity a) {
        ScreenShot.savePic(ScreenShot.takeScreenShot(a), "/sdcard/screen_test.png");
    }

    // 程序入口2
    public static void shootView(View view) {
        ScreenShot.savePic(ScreenShot.convertViewToBitmap(view),
                "sdcard/xx.png");
    }

    public static Bitmap getViewBitmap(View v) {
        v.clearFocus();
        v.setPressed(false);
        boolean willNotCache = v.willNotCacheDrawing();
        v.setWillNotCacheDrawing(false);
        // Reset the drawing cache background color to fully transparent
        // for the duration of this operation
        int color = v.getDrawingCacheBackgroundColor();
        v.setDrawingCacheBackgroundColor(0);
        if (color != 0) {
            v.destroyDrawingCache();
        }
        v.buildDrawingCache();
        Bitmap cacheBitmap = v.getDrawingCache();
        if (cacheBitmap == null) {
            Log.e("TTTTTTTTActivity", "failed getViewBitmap(" + v + ")",
                    new RuntimeException());
            return null;
        }
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
        // Restore the view
        v.destroyDrawingCache();
        v.setWillNotCacheDrawing(willNotCache);
        v.setDrawingCacheBackgroundColor(color);
        return bitmap;
    }

    /**
     * 获取日历的图片
     *
     * @param v
     * @return
     */
    public static Bitmap getCalendarViewBitmap(View v, String wenAn) {
        Context context = v.getContext();
        v.clearFocus();
        v.setPressed(false);
        boolean willNotCache = v.willNotCacheDrawing();
        v.setWillNotCacheDrawing(false);
        // Reset the drawing cache background color to fully transparent
        // for the duration of this operation
        int color = v.getDrawingCacheBackgroundColor();
        v.setDrawingCacheBackgroundColor(0);
        if (color != 0) {
            v.destroyDrawingCache();
        }
        v.buildDrawingCache();
        Bitmap cacheBitmap = v.getDrawingCache();
        if (cacheBitmap == null) {
            Log.e("TTTTTTTTActivity", "failed getViewBitmap(" + v + ")",
                    new RuntimeException());
            return null;
        }
        int marginLeft = DensityUtil.dip2px(context, 20);
        int marginTop = DensityUtil.dip2px(context, 37);
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap.getWidth() + 2 * marginLeft, cacheBitmap
                .getHeight() +
                DensityUtil.dip2px(context, 150) + marginTop, Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);
        canvas.drawBitmap(cacheBitmap, marginLeft, marginTop, null);

        Bitmap logo = BitmapFactory.decodeResource(context.getResources(), R
                .drawable.checked_radio);
//        canvas.drawColor(Color.WHITE);
//        Paint paint = new Paint();
//        paint.setAntiAlias(true);
//        paint.setStrokeWidth(0.5f);

        // 画文案
        TextPaint textPaint = new TextPaint();
        textPaint.setTextSize(DensityUtil.sp2px(context, 14));
        textPaint.setColor(context.getResources().getColor(R.color.gray_green));
        StaticLayout layout = new StaticLayout(wenAn, textPaint, DensityUtil.dip2px(context, 220)
                , Layout.Alignment
                .ALIGN_NORMAL, 1.0F, 0.0F, true);
        canvas.save();
        canvas.translate(DensityUtil.dip2px(context, 107), bitmap.getHeight() - logo
                .getHeight() - DensityUtil.dip2px(context, 38));
        layout.draw(canvas);
        canvas.restore();

        canvas.save();
        canvas.translate(bitmap.getWidth() - DensityUtil.dip2px(context, 90), bitmap.getHeight()
                - DensityUtil.dip2px(context, 37));
        Paint linePaint = new Paint();
        linePaint.setTextSize(DensityUtil.sp2px(context,14));
        linePaint.setColor(context.getResources().getColor(R.color.gray_green));
        linePaint.setStrokeWidth(DensityUtil.dip2px(context,0.5f));
        canvas.drawLine(0, 0, DensityUtil.dip2px(context, 28), 0, linePaint);
        canvas.drawText("友瓣",DensityUtil.dip2px(context, 38),DensityUtil.dip2px(context,5),linePaint);
        canvas.restore();

        // 画二维码
        canvas.drawBitmap(logo, DensityUtil.dip2px(context, 22), bitmap.getHeight() - logo
                .getHeight() - DensityUtil.dip2px(context, 38), null);

        String recordDirectory = Environment.getExternalStorageDirectory().getAbsolutePath() +
                "/uban/ub_pic_temp/";
        File recordDir = new File(recordDirectory);
        // 要保证目录存在，如果不存在则主动创建
        if (!recordDir.exists()) {
            recordDir.mkdirs();
        }

        // 测试输出
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(recordDirectory + "calendar_screen_shot.png");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            LogUtils.i("=====创建图片错误");
        }
        try {
            if (null != out) {
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                out.flush();
                out.close();
            }
        } catch (IOException e) {
            // TODO: handle exception
            LogUtils.i("=====输出图片错误");
        }

        // Restore the view
        v.destroyDrawingCache();
        v.setWillNotCacheDrawing(willNotCache);
        v.setDrawingCacheBackgroundColor(color);
        return bitmap;
    }


    /**
     * 截取scrollview的屏幕
     **/
    public static Bitmap getBitmapByView(ScrollView scrollView) {
        int h = 0;
        Context context = scrollView.getContext();
        Bitmap bitmap = null;
        // 获取listView实际高度
        for (int i = 0; i < scrollView.getChildCount(); i++) {
            h += scrollView.getChildAt(i).getHeight();
//            scrollView.getChildAt(i).setBackgroundResource(R.mipmap.ic_launcher);
        }
        Log.d(TAG, "实际高度:" + h);
        Log.d(TAG, " 高度:" + scrollView.getHeight());
        // 创建对应大小的bitmap
        bitmap = Bitmap.createBitmap(scrollView.getWidth(), h,
                Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);
        scrollView.draw(canvas);
        String recordDirectory = Environment.getExternalStorageDirectory().getAbsolutePath() +
                "/uban/ub_pic_temp/";
        File recordDir = new File(recordDirectory);
        // 要保证目录存在，如果不存在则主动创建
        if (!recordDir.exists()) {
            recordDir.mkdirs();
        }

        // 测试输出
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(recordDirectory + "calendar_screen_shot.png");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            LogUtils.i("=====创建图片错误");
        }
        try {
            if (null != out) {
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                out.flush();
                out.close();
            }
        } catch (IOException e) {
            // TODO: handle exception
            LogUtils.i("=====输出图片错误");
        }

        return bitmap;
    }

    private static String TAG = "tem 截图:";

    /**
     * 截图listview
     **/
    public static Bitmap getbBitmap(ListView listView) {
        int h = 0;
        Bitmap bitmap = null;
        // 获取listView实际高度
        for (int i = 0; i < listView.getChildCount(); i++) {
            h += listView.getChildAt(i).getHeight();
        }
        Log.d(TAG, "实际高度:" + h);
        Log.d(TAG, "list 高度:" + listView.getHeight());
        // 创建对应大小的bitmap
        bitmap = Bitmap.createBitmap(listView.getWidth(), h,
                Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bitmap);
        listView.draw(canvas);
        // 测试输出
        FileOutputStream out = null;
        try {
            out = new FileOutputStream("/sdcard/screen_test.png");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            if (null != out) {
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                out.flush();
                out.close();
            }
        } catch (IOException e) {
            // TODO: handle exception
        }
        return bitmap;
    }
}